package com.briup.ch12;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/20
 * @Description:
 */
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class TCPServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        BufferedWriter bw = null;

        try {
            // 监听端口8002
            serverSocket = new ServerSocket(8002);
            System.out.println("服务器已启动，等待客户端连接...");
            // 接受客户端连接
            socket = serverSocket.accept();
            System.out.println("客户端已连接");

            // 输入流：接收客户端发送的老师对象集合
            ois = new ObjectInputStream(socket.getInputStream());
            ArrayList<Teacher> teachers = (ArrayList<Teacher>) ois.readObject();

            // 遍历输出老师信息
            System.out.println("收到客户端的老师信息：");
            for (Teacher teacher : teachers) {
                System.out.println(teacher);
            }

            // 将老师信息写入本地文件src/t.txt
            bw = new BufferedWriter(new FileWriter("t.txt"));
            for (Teacher teacher : teachers) {
                bw.write(teacher.toString());
                bw.newLine();
            }
            bw.flush();
            System.out.println("老师信息已写入t.txt");

            // 输出流：向客户端返回"ok"响应
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject("ok");
            oos.flush();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (bw != null) bw.close();
                if (ois != null) ois.close();
                if (oos != null) oos.close();
                if (socket != null) socket.close();
                if (serverSocket != null) serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
